package de.wittje.games.mlpbd.controller;

import java.io.InputStream;

import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;
import javazoom.jl.player.advanced.PlaybackListener;

public class BackgroundMusic implements Runnable {

	private Player p;
	private boolean running = true;
	private String track;

	public BackgroundMusic(String track) {
		try {
			this.track = track;
			InputStream in = this.getClass().getResourceAsStream(
					"/de/wittje/games/mlpbd/data/music/" + track + ".mp3");

			p = new Player(in);
		} catch (JavaLayerException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {

		long lastCheck = System.currentTimeMillis();

		try {
			p.play();
			while (running) {

				if (p.isComplete()
						&& System.currentTimeMillis() - lastCheck > 10) {
					InputStream in = this.getClass().getResourceAsStream(
							"/de/wittje/games/mlpbd/data/music/" + track
									+ ".mp3");

					p = new Player(in);
					p.play();
				}

			}
		} catch (JavaLayerException e) {
			e.printStackTrace();
		}

	}

	public void stop() {
		running = false;
	}
}
